<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="70px">
      <el-form-item label="投票名称" prop="voteName">
        <el-select v-model="queryParams.voteName" placeholder="请选择投票" clearable filterable style="width: 200px">
          <el-option 
            v-for="vote in voteOptions" 
            :key="vote.voteId" 
            :label="vote.voteTitle" 
            :value="vote.voteId" 
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
       
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleEdit()"
        
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:post:remove']"
        >删除</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table border v-loading="loading" :data="list" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column prop="page" label="页面路径" min-width="200">
        <template #default="scope">
         {{pageOptions.find(v=>v.value==scope.row.pageUrl).label}}
        </template>
      </el-table-column>
      <el-table-column prop="voteName" label="名称" min-width="150">
        <template #default="scope">
          <span>{{ scope.row.voteName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="communityName" label="社区名称" min-width="120">
        <template #default="scope">
          <span>{{ scope.row.communityName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="picSize" label="尺寸" min-width="80">
        <template #default="scope">
          <span>{{ scope.row.picSize || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="scene" label="投票列表" min-width="150">
        <template #default="scope">
          <el-tooltip :content="scope.row.scene" placement="top" :show-after="500">
            <span class="text-ellipsis">{{ scope.row.scene || '-' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="picUrl" label="二维码" min-width="100">
        <template #default="scope">
          <el-image 
            :src="scope.row.picUrl" 
            style="width: 80px; height: 80px;"
            fit="cover"
            :preview-src-list="[scope.row.picUrl]"
            :initial-index="0"
            preview-teleported
            hide-on-click-modal
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="140" />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改二维码弹窗 -->
    <el-dialog 
    :close-on-click-modal="false"
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="500px" 
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="页面路径" prop="pageUrl" required>
          <el-select v-model="form.pageUrl" 
          placeholder="请选择页面路径" style="width: 100%;">
            <el-option 
              v-for="option in pageOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.pageUrl == 'pages/votingForm/index'" label="投票列表" prop="voteName" required>
          <el-select  @change="handleVoteChange" v-model="form.voteName" placeholder="请选择投票" filterable style="width: 100%;">
            <el-option 
              v-for="vote in voteOptions" 
              :key="vote.voteId" 
              :label="vote.voteTitle" 
              :value="vote.voteId" 
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.pageUrl == 'pages/votinglist/index'" label="类型" prop="type" required>
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%;" @change="handleTypeChange">
            <el-option label="业主大会" :value="1" />
            <el-option label="快速决议" :value="2" />
            <el-option label="问卷调查" :value="3" />
            <el-option label="倡议书" :value="4" />
          </el-select>
        </el-form-item>
         <el-form-item label="尺寸" prop="picSize" required>
            <el-input type="number" min="280" max="1280" v-model="form.picSize" placeholder="请输入尺寸" />
         </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getQrcodeList, generateQrcode, pmsAcodeAdd,deleteQrcode, updateQrcode } from '@/api/house/qrcode'
import { listVote } from '@/api/house/vote'
import Pagination from '@/components/Pagination/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()

const list = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const voteOptions = ref([])
const ids = ref([])
const single = ref(true)
const multiple = ref(true)

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  page: '',
  voteName: ''
})

const form = reactive({
  id: undefined,
  page: '',
  scene: '',
  picSize: 430,
  communityId: "",
  communityName: "",
  voteId: "",
  voteName: "",
  type: undefined
})

// 页面路径选项
const pageOptions = [
  { label: '首页', value: 'pages/home/index' },
  { label: '投票列表页面', value: 'pages/votinglist/index' },
  { label: '投票详情页面', value: 'pages/votingForm/index' }
]

const rules = {
  pageUrl: [
    { required: true, message: '请选择页面路径', trigger: 'change' }
  ],
  voteName: [
    { required: true, message: '请选择投票', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  picSize: [
    { required: true, message: '请输入尺寸', trigger: 'blur' }
  ]
}

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const data = await getQrcodeList(queryParams.value)
    list.value = data?.rows || []
    total.value = data?.total || 0
  } catch (error) {
    console.error('获取二维码列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.value.page = ''
  queryParams.value.voteName = ''
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增二维码'
  dialogVisible.value = true
  resetForm()
}

// 修改
const handleUpdate = (row) => {
  dialogTitle.value = '修改二维码'
  dialogVisible.value = true
  Object.assign(form, row)
}

// 编辑（批量）
const handleEdit = () => {
  if (ids.value.length !== 1) {
    ElMessage.warning('请选择一条记录进行编辑')
    return
  }
  const row = list.value.find(item => item.id === ids.value[0])
  handleUpdate(row)
}

// 删除
const handleDelete = async (row) => {
  const delIds = row ? [row.id] : ids.value
  if (!delIds.length) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm('确认删除选中的二维码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await Promise.all(delIds.map(id => deleteQrcode(id)))
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleVoteChange = (row) => {
  let item = voteOptions.value.find(v => v.voteId === row)
  console.log("item22",item)
  form.type = item.type
  form.voteName = item.voteTitle
  form.scene = `voteId=${item.voteId}&communityId=${item.communityId}`
  form.voteId = row
}

const handleTypeChange = (value) => {
  form.scene = `type=${value}&communityId=${userStore.communityId}`
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
   
    form.communityName = userStore.communityName
    console.log("form",form.type)
    return
    if (!form.scene) {
      if (form.pageUrl == 'pages/votinglist/index' && form.type) {
        form.scene = `type=${form.type}&communityId=${userStore.communityId}`
      } else {
        form.scene = `communityId=${userStore.communityId}`
      }
    }
    
    let data1 = await generateQrcode({
      ...form
    })
  
    dialogVisible.value = false
    getList()
    ElMessage.success('操作成功')
    
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 获取投票列表
const getVoteOptions = async () => {
  try {
    const data = await listVote({ pageNum: 1, pageSize: 1000 })
    voteOptions.value = data?.rows || []
  } catch (error) {
    console.error('获取投票列表失败:', error)
    ElMessage.error('获取投票列表失败')
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: undefined,
    page: '',
    scene: '',
    picSize: 430,
    communityId: '',
    communityName: '',
    voteId: '',
    voteName: '',
    type: undefined
  })
}

onMounted(async () => {
  await getVoteOptions()
  getList()
})
</script>

